package com.weaver.drools.common.utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Utools {
	/**
	 * MD5加密算法
	 * 
	 * @param String
	 *            source = 原加密字符串
	 * 
	 * @return String = 加密后的字符串
	 * 
	 * @author simon
	 * 
	 * @throws NoSuchAlgorithmException
	 * 
	 * @timer 2007-05-01
	 */
	public static String MD5(String source) throws NoSuchAlgorithmException {
		if (source == null || source.length() == 0) {
			System.err.println("警告 ： 空字符串不可以作MD5加密 !");
			return null;
		}
		StringBuffer hexString = new StringBuffer();
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(source.getBytes());
			byte hash[] = md.digest();
			for (int i = 0; i < hash.length; i++) {
				if ((0xff & hash[i]) < 0x10) {
					hexString.append("0"
							+ Integer.toHexString((0xFF & hash[i])));
				} else {
					hexString.append(Integer.toHexString(0xFF & hash[i]));
				}
			}
			return hexString.toString();
		} catch (NoSuchAlgorithmException e) {
			System.err.println("当请求特定的加密算法<MD5>而它在该环境中不可用时抛出此异常");
			throw new NoSuchAlgorithmException(
					"当请求特定的加密算法<MD5>而它在该环境中不可用时抛出此异常");
		}
	}
}
